//
//  ConsultWriteIdealViewController.m
//  yilutongxing
//
//  Created by ios-21 on 17/4/28.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "ConsultWriteIdealViewController.h"
#import "YYText.h"
#import "DzyImgPicker.h"
#import "RPUserInfoBean.h"
#import <MJExtension.h>
#import <GTMBase64.h>
#import <QMUITips.h>
#import "TimeTools.h"

#define URL_sendconsult @"/api/consultations"

@interface ConsultWriteIdealViewController ()<YYTextViewDelegate,DzyImgDelegate,NetworkUtilsDelegate>
@property (weak, nonatomic) IBOutlet UILabel *textFieldTextStringLable;
@property (weak, nonatomic) IBOutlet UILabel *textViewStrLengtLable;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property (weak, nonatomic) IBOutlet UITextField *myTextField;
@property (weak, nonatomic) IBOutlet YYTextView *contentTextView;
@property(nonatomic,strong)DzyImgPicker *DzyView;
@property (nonatomic ) NSMutableArray *data;
@property (weak, nonatomic) IBOutlet UIView *selectedPhotoView;
@property(nonatomic,strong)NSArray *imageArr;
@property(nonatomic,strong)RPUserInfoBean *userInfo;

@end

@implementation ConsultWriteIdealViewController
- (void)textFieldDidChange:(UITextField *)textField {
    if (textField == self.myTextField) {
        if (textField.text.length > 20) {
            textField.text = [textField.text substringToIndex:20];
            [UIView showToastWindowWithMessage:@"字数不能超过20"];
        }
        self.textFieldTextStringLable.text = [NSString stringWithFormat:@"%u/20",textField.text.length];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.confirmBtn.layer.cornerRadius = 20;
    self.confirmBtn.layer.masksToBounds = YES;
    // 添加 UIControlEventEditingChanged  target事件，即可实时监测textField 内容，并做一些操作
    [self.myTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.contentTextView.delegate = self;
    
    self.title = @"图文咨询";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"返回"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    [self selectedPhotoMed];
    
    
    NSDictionary *dic=[UserDefaultsTools getUserDefaultsForKey:USERINFO_KEY];
    self.userInfo=[RPUserInfoBean mj_objectWithKeyValues:dic];
}
- (void)backAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    UIView* contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.backgroundColor = [UIColor blackColor];
    contentView.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT + self.tabBarController.tabBar.frame.size.height);
    
    //从相册返回的话需要刷新下界面
    [_DzyView.collectionView reloadData];
    
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger caninputlen = comcatstr.length;
    
    if (caninputlen <= 500)
    {
        return YES;
    }
    else
    {
        [UIView showToastWindowWithMessage:@"字数不能超过500"];
        return NO;
    }
}
-(void)textViewDidChange:(UITextView *)textView{
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    self.textViewStrLengtLable.text = [NSString stringWithFormat:@"%ld/500",(long)existTextNum];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

//确认发送
- (IBAction)sendAction:(id)sender {
    if (self.imageArr.count>0) {
        NSMutableArray *imgDataArr = [NSMutableArray array];
        for (UIImage *img in self.imageArr) {
            NSData *rawData = UIImageJPEGRepresentation(img, 1.0f);
            NSData *encodedData = [GTMBase64 encodeData:rawData];
            NSString *encodeStr = [[NSString alloc]initWithData:encodedData encoding:NSASCIIStringEncoding];
            [imgDataArr addObject:encodeStr];
        }
        NSDictionary *dic=@{@"name":self.myTextField.text,@"content":self.myTextField.text,@"images":imgDataArr,@"sickId":self.userInfo.user.ID,@"doctorId":[NSNumber numberWithLong:self.doctorUID]};
        [[YZENetwork sharedInstace]postRequestWithUrl:[BASE stringByAppendingString:URL_sendconsult] parameters:dic delegate:self requestTag:1 successBlock:^(id responseObject) {
            [QMUITips hideActivityView];
            NSString *createdDate = [TimeTools getCurrentTimeYMDHMS];
            NSDictionary *selfinfo = @{@"avatar":self.userInfo.avatar};
            NSDictionary *backdata = @{@"isRight":@YES,@"consultationDTO":responseObject, @"dSender":selfinfo, @"createdDate":createdDate};
            [self.delagate sendFinish:backdata];
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        
        [QMUITips showLoadingInView:self.view];
    }else{
        [UIView showToastWindowWithMessage:@"图片不能为空"];
    }
}

-(void)selectedPhotoMed{
    self.data = [NSMutableArray array];
    //此处需要注意  自己计算一下  我设置的每个cell 是60*60  间距10 所以 这里一般是设置 全屏宽度  如有特殊需求自行修改
    
    self.DzyView = [[DzyImgPicker alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH,220) andParentV:self andMaxNum:4];
    self.DzyView.dzyImgDelegate = self;
    [self.selectedPhotoView addSubview:self.DzyView];
    
    __weak typeof(self)weakSelf = self;
    [self.DzyView setDzyImgs:^(NSArray *data) {
        NSLog(@"block --- %lu",(unsigned long)data.count);
        weakSelf.data = [data mutableCopy];
        weakSelf.DzyView.collectionView.frame=CGRectMake(0, 0, SCREEN_WIDTH, 110);
    }];
}


//代理方式返回数组
- (void)getImages:(NSArray *)imgData{
    self.imageArr=imgData;
    NSLog(@"imgData = = = =  7868 7678 = = %@",imgData);
}


#pragma mark - NetworkUtilDelegate
- (void)OnFail:(NSString *)errorMsg errorCode:(NSInteger)errorCode requestTag:(int)tag{
    [QMUITips hideActivityView];
    [QMUITips showError:@"发起失败!" inView:self.view hideAfterDelay:2];
}

@end
